// 小程序接口请求能力
import CONFIG from '../config.js'

// CONFIG.host

let api = {
    // 因小程序端不支持cookie，所以在request中设置cookie携带sessionid以保持会话
    cookie:'',
    setCookie: (respone) => {
        if (respone.header && respone.header['Set-Cookie']) {
            api.cookie = respone.header['Set-Cookie'];
        }
    },
    request: function () {
        var method = arguments[0];
        var url = arguments[1];
        var data = arguments[2];
        let firstTime = new Date().getTime();
        return new Promise(function (resolve, reject) {
            wx.request({
                url: CONFIG.host + url,
                method: method.toUpperCase(),
                data: data,
                dataType: "json",
                header: {
                    // 'content-type': 'application/x-www-form-urlencoded',
                    'Cookie': api.cookie || ''
                },
                success: function (e) {
                    api.setCookie(e);
                    if (e.status == 500) {
                        // utils.showModel('', '服务器错误')
                        reject(e.data);
                        return;
                    }
                    console.log('全局拦截：', method, url, data, e.data, '耗时', new Date().getTime() - firstTime)
                    resolve(e.data);
                },
                fail: function (e) {
                    console.log('错误全局拦截'+ e.errMsg)
                    // utils.showModel('', '服务器错误：' + e.errMsg)
                    reject(e.data);
                }
            })
        });
    }

}
let request = {};
// 封装所有类型的方法
let requestType = ['delete', 'get', 'head', 'options', 'post', 'put', 'patch'];
requestType.forEach(method => {
    request[method] = function () {
        return api.request(method, ...arguments);
    };
})

export default request